package com.itclass.auth.authentication;


import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.itclass.auth.enums.ResultCodeEnum;
import com.itclass.auth.pojo.db.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.*;
import org.springframework.security.web.util.RedirectUrlBuilder;
import org.springframework.security.web.util.UrlUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 没有权限访问，会执行到这里
 */
@Slf4j
public class LoginAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        log.warn("没有登录认证，请求登录认证");
        // 设置响应内容类型为 JSON
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        // 设置响应字符编码为 UTF-8
        response.setCharacterEncoding("UTF-8");
        // 创建一个包含错误信息的 JSON 对象
        String json = JSONUtil.toJsonStr(Result.fail(ResultCodeEnum.LOGIN_AUTH));
        response.getWriter().write(json);

    }

}
